package com.taoshen.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.Console;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.log.StaticLog;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @Description 测试文件上传到redis 再从redis下载
 * @Author Zhang Litao
 * @Date 2022/2/11 9:23
 */
@RestController
@RequestMapping("file")
public class FileUploadAndDownloadController {
    @Autowired
    private StringRedisTemplate template;

    /**
     * 文件上传到redis
     * 返回该文件的key给前端
     */
    @PostMapping("upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        StaticLog.info("文件名称 => {}", file.getOriginalFilename());

        String uuid = IdUtil.fastUUID();
        template.opsForValue().set(uuid, Base64.encode(file.getInputStream()));

        return uuid;
    }


    /**
     * 文件下载从redis
     * 前端传递文件唯一标识到后端
     */
    @GetMapping("download")
    public void downloadFile(HttpServletResponse response, @RequestParam("fileId") String fileId) throws IOException {
        response.setHeader("content-disposition","attachment;fileName=" + URLUtil.encode("用户导入模板.xlsx", CharsetUtil.UTF_8));
        String encodeFile = template.opsForValue().get(fileId);
        ServletOutputStream outputStream = response.getOutputStream();

        Base64.decodeToStream(encodeFile, outputStream, true);
    }
}
